package io.esirong.base;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import io.esirong.util.ARouterUtils;

/**
 * 承载显示Fragment(直接使用，用承载Fragment页面)
 * 通过{@link #P_OPTION_FRAGMENT_PATH} 设置fragment
 * 或者重写方法{@link #initFragment()}返回Fragment
 */
public final class FragmentActivity extends BaseActivity {

    Fragment currentFragment;
    /**
     * 结合路由完成
     */
    public final static String P_OPTION_FRAGMENT_PATH = "fragment_uri";
    public final static String P_SOFT_INPUT_MODEL = "softInputModel";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Bundle args = getIntent().getExtras();
        super.onCreate(savedInstanceState);

        FrameLayout fragmentContainer = new FrameLayout(this);
        fragmentContainer.setLayoutParams(new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        fragmentContainer.setId(R.id.content_container);
        setContentView(fragmentContainer);

        Fragment fragment = initFragment();
        if (fragment != null) {
            //直接把参数传递过去
            fragment.setArguments(args);
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();   // 开启一个事务
            transaction.replace(R.id.content_container, fragment);
            transaction.commit();
        }
    }

    @Override
    protected void initView(View view) {

    }

    /**
     * 子类可以复写此方法，返回一个{@link Fragment}
     *
     * @return {@link Fragment}
     */
    protected Fragment initFragment() {
        String uri = getIntent().getStringExtra(P_OPTION_FRAGMENT_PATH);

        if (!TextUtils.isEmpty(uri)) {
            //通过路由工具获取实例
            currentFragment = ARouterUtils.getFragment(uri);

            //尝试反射实例化
            if (currentFragment == null) {
                try {
                    currentFragment = (Fragment) Class.forName(uri).newInstance();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                }
            }
        }

        return currentFragment;
    }

}
